package soar.template.springboot.command.process.app;

import java.util.Arrays;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;

import soar.template.springboot.command.process.configuration.mysql.MyMySQLConfiguration;

@Component
public class App implements CommandLineRunner
{
    private final static Logger logger = LoggerFactory.getLogger(App.class);

     @Resource(name = "mainEntityManagerFactory")
     private EntityManagerFactory mainEntityManagerFactory;


    @Override
    public void run(String... args) throws Exception
    {
        EntityManager main_em = null;

        try
        {
            main_em = mainEntityManagerFactory.createEntityManager();

            main_em.getTransaction().begin();

            logger.info("Hello world: args -> {}",
                    Arrays.asList(args).stream()
                            .map(x -> String.format("(%s)", x))
                            .collect(Collectors.joining(" ")));

            main_em.getTransaction().commit();

            Thread.sleep(5 * 1000);
        }
        catch (Exception e)
        {
            logger.error("fail: {}", e);
            try
            {
                if (main_em != null && main_em.getTransaction().isActive())
                    main_em.getTransaction().rollback();
            }
            catch (Exception er)
            {
                logger.error("rollback fail: {}", er);
            }
        }
        finally
        {
            if (main_em != null)
                main_em.close();
        }

        System.exit(0);
    }
}
